package com.schoolgard.action.system;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.schoolegard.services.CatalogService;
import com.schoolegard.services.RoleService;
import com.schoolgard.base.BaseAction;
import com.schoolgard.entitybean.GridDataModel;
import com.schoolgard.entitybean.Role;
import com.schoolgard.entitybean.RoleHelp;
import com.schoolgard.entitybean.RolePrivilege;

public class RoleAction extends BaseAction{
    
	private static Logger logger = Logger.getLogger(RoleAction.class);
	private static final long serialVersionUID = 201112052117L;
	
	
	private RoleService roleService;
	private CatalogService catalogService;
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
	public void setCatalogService(CatalogService catalogService) {
		this.catalogService = catalogService;
	}
	private Role r;
	public Role getR() {
		return r;
	}
	public void setR(Role r) {
		this.r = r;
	}



	public void findAllRole()
	{
		String startStr = request.getParameter("start"); //grid传过来的当前数据条数
		 String limitStr = request.getParameter("limit"); //每页显示的数据数
		 
		 int start = Integer.parseInt(startStr);
	     int limit = Integer.parseInt(limitStr);
	     if (limit == 0) {
	    	 limit = Integer.MAX_VALUE;
	     }
	     int end = start + limit;  //当前页需要显示的数据 start--> end
	     RoleHelp rolehelp = null;
	     List<RoleHelp> rolehelps = new ArrayList<RoleHelp>();
		List<Role> roles = roleService.findAllRole(); 
		for (Role role2 : roles) {
			rolehelp = new RoleHelp();
			rolehelp.setEnable(role2.getEnable());
			rolehelp.setId(role2.getId());
			rolehelp.setName(role2.getName());
			rolehelps.add(rolehelp);
		}
		int total = roles.size();
		if(end > total)end = total;
		
		GridDataModel<RoleHelp> page = new GridDataModel<RoleHelp>();
		page.setPage(start/limit + 1);
		page.setRows(rolehelps);
		page.setTotal(total);
		String jsonStr = JSONObject.fromObject(page).toString();
		writeToResponse(jsonStr);
	}
	
	public void saveRole()
	{
		Role role = null;
		if(r.getId() == null || r.getId() == 0){
			role = new Role();
		}else{
			role = roleService.findById(r.getId());
		}
		role.setName(r.getName());
		role.setEnable(true);
		roleService.saveOrUpdate(role);
		writeToResponse("1");
	}
	
	public void deleteRole()
	{
		String id = request.getParameter("id");
		if(StringUtils.isBlank(id)){
			writeToResponse("0");
			return;
		}else{
			roleService.delete(Long.valueOf(id));
			writeToResponse("1");
		}
	}
	
	/**
	 * 只留下叶子节点，去掉父节点ID
	 * @param nodes
	 * @return
	 */
	private String selectLeafNode(String nodes)
	{
		if(StringUtils.isBlank(nodes)) return "";
		String[] nodeArray = nodes.split(",");
		List<String> leafNodes = new ArrayList<String>();
		List<String> retNodes = new ArrayList<String>();
		for (String str : nodeArray) {
			leafNodes.add(str);
			retNodes.add(str);
		}
		for (int i=0 ; i<leafNodes.size() ; i++) {
			for (int j=i ; j<leafNodes.size() ; j++) {
				if(leafNodes.get(i).length() < leafNodes.get(j).length() && 
						StringUtils.equals(leafNodes.get(i), leafNodes.get(j).substring(0,leafNodes.get(i).length()))){
					retNodes.remove(leafNodes.get(i));
					break;
				}
			}
		}
		return retNodes.toString();
	}
	
	public void findMyCatalog()
	{
		String roleId = request.getParameter("roleId");
		List<RolePrivilege> catalogAuthority = catalogService.findByRoleId(Long.valueOf(roleId)); 
		if(catalogAuthority != null && catalogAuthority.size() > 0){
			RolePrivilege tca = catalogAuthority.get(0);
			String leafNodes = selectLeafNode(tca.getPrivilegeMenu());
			writeToResponse(leafNodes);
		}else{
			writeToResponse("0");
		}
	}
	
	public void saveAuthority()
	{
		String ids = request.getParameter("catalogIds");
		String roleId = request.getParameter("roleId");
		List<RolePrivilege> tcas = catalogService.findByRoleId(Long.valueOf(roleId));
		RolePrivilege tca = (tcas != null && tcas.size() > 0)?tcas.get(0):null;
		if(tca == null){
			tca = new RolePrivilege();
			tca.setRole(roleService.findById(Long.valueOf(roleId)));
		}
		tca.setPrivilegeMenu(ids);
		try{
			catalogService.saveRolePrivilege(tca);
		}catch(Exception e){
			e.printStackTrace();
			writeToResponse("0");
		}
		writeToResponse("1");
	}
	
}
